package com.jiepos.mpos.biz.appInfM.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.DBConstant;
import com.jiepos.mpos.common.dao.AppLogErrorReportDao;
import com.jiepos.mpos.common.entity.App_Log_ErrorReportEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.DateUtil;
import com.jiepos.mpos.core.util.FileUtils;
import com.jiepos.mpos.core.util.GlobalUtils;
import com.jiepos.mpos.core.util.StringUtils;


/**
 *
 *
 * <p>标题: —— 错误日志类</p>
 * <p>模块: 通用平台</p>
 * <p>版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
 * @ProjectName:  [mpos]
 * @Package com.jiepos.mpos.biz.appInfM.service
 * @author 余翼膑
 * @version 1.0
 * @since 2018年2月08号
 * @history（历次修订内容、修订人、修订时间等）
 */
@Service
public class LogErrorReportService extends BaseService {



    @Autowired
    private AppLogErrorReportDao appLogErrorReportDao;


    /**
     * 查询通知公告信息列表json分页数据
     *
     * @param pagination
     * @param appLogErrorReportEntity
     * @return
     */
    public Map getErrorReportList(HttpServletRequest request, Pagination pagination, App_Log_ErrorReportEntity appLogErrorReportEntity,String start_date,String end_date) {

        StringBuffer sqlBuf = getInitSql("t1").append(",");
        sqlBuf.append("  T1.REPORT_UUID as uuid , ")
                .append(" t1.login_id,t1.app_type,t1.app_id, ")
                .append(" t1.client_version,t1.systemuuid,t1.systemname, ")
                .append(" t1.systemversion, ")
                .append(" t1.systemdevicemodel,t1.file_path  ")
                .append(" FROM "+ DBConstant.Table.T_APP_LOG_ERRORREPORT+" T1 where 1=1  ");
        List list = new ArrayList();
        //app得唯一编号
        if (!StringUtils.isBlank(appLogErrorReportEntity.getApp_id())) {
            sqlBuf.append( " and t1.app_id like ? " );
            list.add("%" + appLogErrorReportEntity.getApp_id() + "%");
        }
        //app类型
        if (!StringUtils.isBlank(appLogErrorReportEntity.getApp_type())) {
            sqlBuf.append( " and t1.app_type like ? " );
            list.add("%" + appLogErrorReportEntity.getApp_type() + "%");
        }
        //起止日期
        if (!StringUtils.isBlank(start_date)) {
            Date dateParam = DateUtil.strToDate(start_date, DateUtil.FORMAT_DATE_1);
            sqlBuf.append("and TO_CHAR(t1.rec_crt_ts,'yyyy-MM-dd') >= ? ");
            list.add(DateUtil.dateToStr(dateParam, "yyyy-MM-dd"));
        }
        if (!StringUtils.isBlank(end_date)) {
            Date dateParam = DateUtil.strToDate(end_date, DateUtil.FORMAT_DATE_1);
            sqlBuf.append("and TO_CHAR(t1.rec_crt_ts,'yyyy-MM-dd') <= ? ");
            list.add(DateUtil.dateToStr(dateParam, "yyyy-MM-dd"));
        }

        pagination.queryString = sqlBuf.toString();
        pagination = this.getOrderSql(pagination, "t1");
        return appLogErrorReportDao.getPaginationMap(pagination,"t1",list);
    }

    /**
     *
     * @param fileName
     *            文件名
     *            输入文件流
     * @param response
     */
    public void downloadFile(String fileName, HttpServletResponse response, HttpServletRequest request) {
        OutputStream toClient = null;
        //String hostName = SystemConstant.ERROR_FILE_UPLOAD_PATH.trim();
        String errFilePath = GlobalUtils.getAppPath().substring(0,GlobalUtils.getAppPath().length()-1) + fileName;

        // 设置要查找的路径
        log.debug("查看的目录 path:" + errFilePath);
        try {
            File file = new File(errFilePath);
             if (!file.exists()) {
             log.debug(file + "文件不存在！");
            return;
        }
            log.debug("查看的文本 file:" + file);
            InputStream inputStream = new FileInputStream(file);

            InputStream fis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setStatus(200);
            Cookie cookie = new Cookie("fileDownload", "true");
            cookie.setPath("/");
            response.addCookie(cookie);
            toClient = new BufferedOutputStream(response.getOutputStream());

            toClient.write(buffer);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (toClient != null) {
                    toClient.flush();
                    toClient.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }


    /**
     * 根据记录id查询实体对象
     *
     * @param report_uuid
     * @return
     */
    public Map getErrorReportById(String report_uuid) {
        if (StringUtils.isBlank(report_uuid) || report_uuid.equals("undefined")) {
            return new HashMap();
        }
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT T.REPORT_UUID as uuid , ")
                .append(" t.login_id,t.app_type,t.app_id, ")
                .append(" t.client_version,t.systemname, ")
                .append(" t.systemuuid,t.systemversion, ")
                .append(" t.systemdevicemodel,t.file_path  ")
                .append(" FROM "+ DBConstant.Table.T_APP_LOG_ERRORREPORT+" T  where t.report_uuid = ? ");

        List<String> list = new ArrayList<>();
        list.add(report_uuid);
        List<Map<String, Object>> results = appLogErrorReportDao.queryForList(getOrderSql(sqlBuf.toString(), "t"), list);
        if(results != null && results.size() > 0){
            Map reportMap = results.get(0);
            String  filePath = String.valueOf(reportMap.get("file_path"));
            String errFilePath = GlobalUtils.getAppPath().substring(0,GlobalUtils.getAppPath().length()-1)+filePath;
            log.debug("errFilePath="+errFilePath);
            String errTxt = FileUtils.read(errFilePath);
            log.debug("errTxt="+errTxt);
            reportMap.put("errTxt",errTxt);
            return reportMap;

        }
        return new HashMap();
    }

}
